package xyz.zhouzhousag.server.common.utils;
/**
 * Description:
 * <p>
 * ClassName: JwtCredentialsMatcher
 * date: 2021/9/26 18:01
 *
 * @author Yin.Liu
 * @version 1.0
 * @since JDK 1.8
 */

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.stereotype.Component;

/**
 *@ClassName JwtCredentialsMatcher
 *@Description 验证JwtToken的内容是否合法,是realm的凭证校验器
 *@Author Yin.Liu8
 *@Date 2021/9/26 18:01
 *@Version 1.0
 */
@Component
public class JwtCredentialsMatcher implements CredentialsMatcher {
    /**
     * JwtCredentialsMatcher只需验证JwtToken内容是否合法
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {

        String token = authenticationToken.getCredentials().toString();
        String username = authenticationToken.getPrincipal().toString();
        try {
            Algorithm algorithm = Algorithm.HMAC256(JwtUtils.SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}

